package co.fitstart.admin.web.controller.user;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.search.SourceSearch;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.handler.UserHandler;
import co.fitstart.admin.service.CourseRoundService;
import co.fitstart.admin.service.DataService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.service.StudentService;
import co.fitstart.admin.service.UserSourceService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.site.Site;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.UserSource;
import co.fitstart.entity.user.UserSourceRecord;
import co.fitstart.entity.user.UserSourceStatus;
import co.fitstart.entity.user.UserSourceType;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/user-source")
@MenuSetting("menu-source")
public class SourceCreateController {

	private static final Logger logger = LoggerFactory.getLogger(SourceCreateController.class);

	@Autowired
	private SiteService siteService;

	@Autowired
	private PrincipalService principalService;

	@Autowired
	private UserSourceService userSourceService;
	
	@Autowired
	private StudentService studentService;
	
	@Autowired
	private CourseRoundService courseRoundService;
	
	@Autowired
	private UserHandler userHandler;
	
	@Autowired
	@Qualifier("dataService")
	private DataService<UserSourceType> userSourceTypeService;

	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView list(@Secure Login login, 
							 @RequestParam(name = "site", required = false) Long siteId, 
							 @RequestParam(name = "status", required = false, defaultValue = "NOORDER") String status,
							 Page page,
			HttpServletRequest request) {

		ModelAndView modelAndView = new ModelAndView("source/user-source-list");

		Site site = null;
		if (!login.hasSite() && siteId != null) {
			site = siteService.load(siteId);
		} else if (login.hasSite()) {
			site = login.getSite();
		}

		List<UserSource> userSources = new ArrayList<>();

		if (site == null && (login.isAreaManager() || login.isAreaServer())) {
			Principal principal = principalService.load(Principal.class, login.getId());

			List<Site> sites = siteService.listSite(principal);

			if (!sites.isEmpty()) {
				userSources = userSourceService.listSource(sites, page, UserSourceStatus.valueOf(status));
			}
		} else {
			userSources = userSourceService.listSource(site, page, UserSourceStatus.valueOf(status));
		}

		modelAndView.addObject("status", status);
		modelAndView.addObject("userSources", userSources);
		modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));

		return modelAndView;
	}

	/**
	 * 
	 * @param site
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView search(@RequestParam(name = "site", required = false) Long site) {

		ModelAndView modelAndView = new ModelAndView("source/user-source-search");

		modelAndView.addObject("site", site);
		return modelAndView;
	}

	/**
	 * 
	 * @param roundSearch
	 * @param status
	 * @param experience
	 * @param page
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
	@MenuSetting("submenu-source-create-management")
	public ModelAndView onSearch(@Secure Login login, SourceSearch sourseSearch, Page page,
			HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("source/user-source-list");

		if (login.isAreaManager() || login.isAreaServer()) {
			Principal principal = principalService.load(Principal.class, login.getId());

			List<Site> sites = siteService.listSite(principal);

			sourseSearch.setSites(sites);
		}

		if (sourseSearch.getSites() == null || !sourseSearch.getSites().isEmpty()) {
			List<UserSource> userSources = userSourceService.search(sourseSearch, page);
			modelAndView.addObject("userSources", userSources);
		}

		modelAndView.addObject("site", sourseSearch.getSite());

		modelAndView.addObject("page", page);

		modelAndView.addObject("refer", "search");
		modelAndView.addObject("pagetype", "individual");
		modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
		modelAndView.addObject("queryPattern",
				WebUtils.extractQueryString(request, "status", "experience", "give", "page", "site"));
		return modelAndView;
	}
	
	/**
	 * 
	 * @param login
	 * @param sourceId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView view(@Secure Login login, @PathVariable("id") Long sourceId,  HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("source/user-source-view");
		
		UserSource userSource = userSourceService.load(UserSource.class, sourceId);
		modelAndView.addObject("userSource", userSource);
		
		List<UserSourceRecord> userSourceRecords = userSourceService.listRecords(userSource);
		modelAndView.addObject("userSourceRecords", userSourceRecords);
		
		Student student = studentService.load(userSource.getMobile());
		
		if(student != null) {
			List<CourseRound> courseRounds = courseRoundService.listAll(student);
			modelAndView.addObject("courseRounds", courseRounds);
		}
		
		return modelAndView;
	}
	
	@RequestMapping(value = "/refresh-type", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView refresh(@Secure Login login, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("source/user-source-create");
		
		userSourceService.refreshAllType();
		
		return modelAndView;
	}
	

	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView create(@Secure Login login, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("source/user-source-create");
		return modelAndView;
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
    public @ResponseBody String onCreateUserSource(
    		@RequestParam(name = "mobile", required = false) String mobile,
    		@RequestParam(name = "name", required = false) String name,
    		@RequestParam(name = "siteId", required = false) Long siteId,
    	    @RequestParam(name = "wechatnumber", required = false) String wechatnumber,
    	    @RequestParam(name = "gender", required = false) String gender,
    	    @RequestParam(name = "requirement", required = false) String requirement,
    	    @RequestParam(name = "receiver", required = false) Long receiver,
    	    @RequestParam(name = "occurDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date occurDate,
    	    @RequestParam(name = "phoneReciver", required = false) Long phoneReciver,
    	    @RequestParam(name = "userSourceType", required = false) Long userSourceType,
    	    @RequestParam(name = "newSourceChannel", required = false) String newSourceChannel) {
        
        Result result = new Result();
        
        try {
        	
        	Site site = siteService.load(siteId);
        	
        	userSourceService.create(occurDate, site, name, mobile, gender, wechatnumber, requirement, receiver, phoneReciver, userSourceType, newSourceChannel);
        	
        	result.success().message("添加成功");
            
        } catch (BusinessException e) {
        	result.fail(e.getCode()).message(e.getMessage()).data("url", "/user-source/create-record?mobile=" + mobile + "&reciver=" + receiver + "&reason=" + requirement);
            logger.error("error: ", e);
		} catch (Exception e) {
            result.fail().message(e.getMessage());
            logger.error("error: ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
	
	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView edit(@Secure Login login, @PathVariable("id") Long id, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("source/user-source-edit");
		UserSource userSource = userSourceService.load(UserSource.class, id);
        modelAndView.addObject("userSource", userSource);
		return modelAndView;
	}
	
	/**
	 * 
	 * @param id
	 * @param remark
	 * @return
	 */
	@RequestMapping(value = "/{id}/edit", method = RequestMethod.POST)
    public @ResponseBody String onEdit(@Preloading UserSource userSource,
    									@RequestParam("receiverId") Long receiverId,
    									@RequestParam("userSourceTypeId") Long userSourceTypeId) {
        
        Result result = new Result();
        
        try {
        	
        	Principal principal = principalService.load(Principal.class, receiverId);
        	userSource.setReceiver(principal);
        	
        	UserSourceType userSourceType = userSourceTypeService.load(UserSourceType.class, userSourceTypeId);
        	userSource.setUserSourceType(userSourceType);
        	
        	userSourceService.update(userSource);
        	result.success().message("标记成功");
            
        } catch (Exception e) {
            result.fail().message(e.getMessage());
            logger.error("error: ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
	
	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/{id}/return", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView doreturn(@Secure Login login, @PathVariable("id") Long id, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("source/user-source-return");
		modelAndView.addObject("id", id);
		return modelAndView;
	}
	
	/**
	 * 
	 * @param id
	 * @param remark
	 * @return
	 */
	@RequestMapping(value = "/{id}/return", method = RequestMethod.POST)
    public @ResponseBody String onReturn(@PathVariable("id") Long id,
    		@RequestParam(name = "remark") String remark) {
        
        Result result = new Result();
        
        try {
        	
        	UserSource userSource = userSourceService.load(UserSource.class, id);
        	userSource.setUserSourceStatus(UserSourceStatus.RETURN);
        	userSource.setRequirement(remark);
        	userSourceService.update(userSource);
        	
        	result.success().message("标记成功");
            
        } catch (Exception e) {
            result.fail().message(e.getMessage());
            logger.error("error: ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
	
	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/import", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView importUserSource(@Secure Login login, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("source/user-source-import");
		return modelAndView;
	}
	
	/**
	 * 
	 * @param login
	 * @param siteId
	 * @param sourceList
	 * @return
	 */
	@RequestMapping(value = "/import", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ModelAndView onImport(@Secure Login login,
    							 @RequestParam("siteId") Long siteId,
    							 @RequestParam("sourceList") MultipartFile sourceList) {
		ModelAndView modelAndView = new ModelAndView("redirect:/user-source");
		
		try {
			
			List<UserSource> userSources = userHandler.listUserSource(sourceList.getInputStream());
			
			Site site = siteService.load(siteId);
			userSourceService.batchCreate(userSources, site);
			
			modelAndView.addObject("errorMessage", "导入成功");
			return modelAndView;
		} catch (IOException e) {
		
			e.printStackTrace();
            modelAndView.addObject("errorMessage", "导入失败");
            return modelAndView;
		}
		
	}

	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/create-record", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView createRecord(@RequestParam("mobile") String mobile, HttpServletRequest request) {

		ModelAndView modelAndView = new ModelAndView("source/user-source-create-record");

		return modelAndView;
	}
	
	@RequestMapping(value = "/create-record", method = RequestMethod.POST)
    public @ResponseBody String onCreateRecord(
    		@RequestParam(name = "mobile", required = false) String mobile,
    		@RequestParam(name = "siteId", required = false) Long siteId,
    	    @RequestParam(name = "description", required = false) String description,
    	    @RequestParam(name = "remark", required = false) String remark,
    	    @RequestParam(name = "receiver", required = false) Long receiver,
    	    @RequestParam(name = "type", required = false) String type) {
        
        Result result = new Result();
        
        try {
        	
        	Site site = siteService.load(siteId);
        	
        	UserSource userSource = userSourceService.load(mobile);
        	
        	userSourceService.createRecord(site, userSource, type, description, remark, receiver);
        	
        	result.success().message("添加成功").data("url", "/user-source/"+ userSource.getId());
            
        } catch (Exception e) {
            result.fail().message(e.getMessage());
            logger.error("error: ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }

	/**
	 * 
	 * @param request
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/{sourceId}/create-record", method = RequestMethod.GET)
	@MenuSetting("submenu-source-create-management")
	public ModelAndView detailCreateRecord(@PathVariable("sourceId") Long sourceId) {

		ModelAndView modelAndView = new ModelAndView("source/detail-create-record");

		UserSource userSource = userSourceService.load(UserSource.class, sourceId);
		modelAndView.addObject("userSource", userSource);
		
		return modelAndView;
	}


}
